package com.bizihang.common.security.core.code.image;

import com.bizihang.common.security.core.SecurityConstants;
import com.bizihang.common.security.core.code.AbstractValidateCodeProcessor;
import com.bizihang.common.security.core.code.ValidateCodeGenerator;
import com.bizihang.common.security.core.code.ValidateCodeRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.EnumMap;
import java.util.Map;

/**
 * 图片验证码处理器
 *
 * @author paascloud.net @gmail.com
 */
@Component("imageValidateCodeProcessor")
public class ImageCodeProcessor extends AbstractValidateCodeProcessor<ImageCode> {

	public ImageCodeProcessor(Map<String, ValidateCodeGenerator> validateCodeGenerators, ValidateCodeRepository validateCodeRepository) {
		super(validateCodeGenerators, validateCodeRepository);
	}

	/**
	 * 发送图形验证码，将其写到响应中
	 *
	 * @param request   the request
	 * @param imageCode the image code
	 * @throws Exception the exception
	 */
	@Override
	protected void send(ServletWebRequest request, ImageCode imageCode) throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		HttpServletResponse response = request.getResponse();
		try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
			ImageIO.write(imageCode.getImage(), "JPEG", bos);
			EnumMap result = new EnumMap(SecurityConstants.RetEnum.class);
			result.put(SecurityConstants.RetEnum.success, true);
			result.put(SecurityConstants.RetEnum.body, bos.toByteArray());
			String json = objectMapper.writeValueAsString(result);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(json);
		}
	}
}
